<?

class view_sql
{
    private $sql;
    private $num_for_page;
    private $name;
    private $paginator;
    private $page_key;
    private $arrayView;
    function __construct($sql, $total_count = 0, $num_for_page = 20, $name = false, $page_key = 'page', $pages_count = 10)
    {
        $this->sql = $sql;
        $this->num_for_page = $num_for_page;
        $this->name = $name;
        $this->page_key = $page_key;
        if(!$total_count) $total_count = $this->num_for_page;
        $this->paginator = new CPaginator($total_count, $this->num_for_page, $pages_count, $this->page_key);
        $sql = $this->sql." limit {$this->paginator->getOffset()}, {$this->num_for_page}";
        $data = Database::select($sql, false);
        $this->arrayView = new view_array($data, $this->name);
    }
    
    public function getPaginator(){
        return $this->paginator;
    }
    
    public function getArrayView(){
        return $this->arrayView;
    }
    
    public function htmlView()
    {
        
        $out = "";
        $out .= "<div class='sqlview {$this->name}'>";
        $pag = "<div class='paginator'>";
        $first = $this->paginator->getFirstPageLink();
        if($this->paginator->isPageFirst())
            $pag .= "<span class='page selected'>&#171;</span>";
        else
            $pag .= "<span class='page'><a href='{$first}'>&#171;</a></span>";
        foreach($this->paginator->pagelinks() as $key=>$one){
            if($one['selected'])
                $pag .= "<span class='page selected'>{$one['index']}</span>";
            else
                $pag .= "<span class='page'><a href='{$one['link']}'>{$one['index']}</a></span>";
        }
        $last = $this->paginator->getLastPageLink();
        if($this->paginator->isPageLast())
            $pag .= "<span class='page selected'>&#187;</span>";
        else
            $pag .= "<span class='page'><a href='{$last}'>&#187;</a></span>";
        $pag .= "</div>";
        if($this->paginator->pageCount() > 1) $out .= $pag;
        $out .= $this->arrayView->htmlView();
        if($this->paginator->pageCount() > 1) $out .= $pag;
        $out .= "</div>";
        return $out;
    }
    
    public function getOutput(){
        return $this->htmlView();
    }

}

?>